//
//  RunInViewController.m
//  FitTime
//
//  Created by 赵建平 on 16/4/6.
//  Copyright © 2016年 赵建平. All rights reserved.
//

#import <CoreMotion/CoreMotion.h>
#import "RunInViewController.h"
#import "GiFHUD.h"
#import "MZTimerLabel.h"

@interface RunInViewController ()

@property (nonatomic, strong) CMMotionManager *motionManager;
@property (nonatomic, assign) NSTimer *upTimer;
@property (nonatomic, strong) UIView *downView;
@property (nonatomic, strong) UILabel *distanceLabel;
@property (nonatomic, strong) UILabel *velocityLabel;
@property (nonatomic, strong) MZTimerLabel *timeLabel;
@property (nonatomic, strong) UIButton *finshedButton;
@property (nonatomic, strong) UIButton *pauseButton;
@property (nonatomic, assign) BOOL isContinue;
@property (nonatomic, assign) NSTimeInterval sumTime; // 累计步行时间
@property (nonatomic, strong) UIAlertController *alertController;
@property (nonatomic, strong) CMPedometer *pedometer;


@end

@implementation RunInViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.isContinue = YES;
    [self createRunView];
    [self createDownView];
    
    
    
    
    
}

#pragma 加速计
- (void)viewWillAppear:(BOOL)animated {
    
//    [super viewWillAppear:animated];
    self.navigationController.tabBarController.tabBar.hidden = YES;
//
//    self.upTimer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(upDateDisplay) userInfo:nil repeats:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    self.navigationController.tabBarController.tabBar.hidden = NO;
    [GiFHUD dismiss];
}

//- (void)upDateDisplay {
//    
//    // 如果CMMotionManager的加速度数据可用
//    if (self.motionManager.accelerometerAvailable)
//    {
//        // 主动请求获取加速度数据
//        CMAccelerometerData* accelerometerData = self.motionManager.accelerometerData;
//        self.distanceLabel.text  = [NSString stringWithFormat:
//                                         @" %+.2f\nY轴: %+.2f\nZ轴: %+.2f",
//                                         accelerometerData.acceleration.x,
//                                         accelerometerData.acceleration.y,
//                                         accelerometerData.acceleration.z];
//        
//        NSLog(@"%@", self.distanceLabel.text);
//    }
//    
////    if (self.motionManager.accelerometerAvailable) {
////        CMAccelerometerData *accelerometerDara = self.motionManager.accelerometerData;
////        
////        
////        self.distanceLabel.text = [NSString stringWithFormat:@"%+.2f", accelerometerDara.acceleration.x];
////        
//////        if (accelerometerDara.acceleration.z > 1) {
////            CGFloat distance = 0;
////            distance += 1;
////            NSLog(@"%f", accelerometerDara.acceleration.x);
////            NSLog(@"%f", accelerometerDara.acceleration.y);
////            NSLog(@"%f", accelerometerDara.acceleration.z);
//////        }
////        
////    }
//}

- (void)createRunView
{
    UIView *runView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, SCREENWIDTH, SCREENHEIGHT / 2)];
    [self.view addSubview:runView];    
    [GiFHUD setGifWithImageName:@"runningman.gif"];
    [GiFHUD show];
}

- (void)createDownView {
    self.downView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height / 2, SCREENWIDTH, self.view.frame.size.height / 2)];
    self.downView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.downView];
    
    //      downView上布局
    self.distanceLabel = [UILabel labelWithFrame:CGRectZero color:[UIColor clearColor] alignment:NSTextAlignmentCenter];
    [self.downView addSubview:self.distanceLabel];
    [self.distanceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.downView.mas_top).offset(10 * SCALEHEIGHT);
        make.centerX.equalTo(self.downView.mas_centerX);
        make.height.equalTo(@(50 * SCALEHEIGHT));
    }];
    self.distanceLabel.text = @"0";
    self.distanceLabel.font = [UIFont systemFontOfSize:50 *SCALEWIDTH];

   
        
        // 如果计步服务可用
        if([CMPedometer isStepCountingAvailable])
        {

            
            NSDate *localDate = [NSDate date];
            [self.pedometer startPedometerUpdatesFromDate:localDate withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
                self.distanceLabel.text = [NSString stringWithFormat:@"%@" , pedometerData.numberOfSteps];
            }];
        }
        else
        {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您的设备不支持记步" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self.navigationController popViewControllerAnimated:YES];
                self.navigationController.tabBarController.tabBar.hidden = NO;
            }];
            
            [alertController addAction:alertAction];
            [self presentViewController:alertController animated:YES completion:nil];
        
        }
    // 距离文字label
    UILabel *disLabel = [UILabel labelWithFrame:CGRectZero color:[UIColor clearColor] alignment:NSTextAlignmentCenter];
    [self.downView addSubview:disLabel];
    [disLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.distanceLabel.mas_bottom);
        make.centerX.equalTo(self.downView.mas_centerX);
        make.height.equalTo(@(20 * SCALEHEIGHT));
    }];
    disLabel.text = @"跑步总里程(公里)";
    //  时间Label
    self.timeLabel = [MZTimerLabel new];
    [self.downView addSubview:self.timeLabel];
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.downView.mas_top).offset(130 * SCALEHEIGHT);
        make.centerX.equalTo(self.downView.mas_centerX).offset(-100 * SCALEWIDTH);
        make.height.equalTo(@(30 * SCALEHEIGHT));
    }];
    self.timeLabel.text = @"00:00:00";
    self.timeLabel.font = [UIFont systemFontOfSize:30 * SCALEWIDTH];
    
    //  开始计时
    [self.timeLabel start];
    
    
    // 时间文字label
    UILabel *timLabel = [UILabel labelWithFrame:CGRectZero color:[UIColor clearColor] alignment:NSTextAlignmentCenter];
    [self.downView addSubview:timLabel];
    [timLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.timeLabel.mas_bottom);
        make.centerX.equalTo(self.timeLabel.mas_centerX);
        make.height.equalTo(@(20 * SCALEHEIGHT));
    }];
    timLabel.text = @"时长";
    
    //  平均速度Label
    self.velocityLabel = [UILabel labelWithFrame:CGRectZero color:[UIColor clearColor] alignment:NSTextAlignmentCenter];
    [self.downView addSubview:self.velocityLabel];
    [self.velocityLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.downView.mas_top).offset(130 * SCALEHEIGHT);
        make.centerX.equalTo(self.downView.mas_centerX).offset(100 * SCALEWIDTH);
        make.height.equalTo(@(30 * SCALEHEIGHT));
    }];
    self.velocityLabel.text = @"00'00''";
    self.velocityLabel.font = [UIFont systemFontOfSize:30 * SCALEWIDTH];
    // 时间文字label
    UILabel *velLabel = [UILabel labelWithFrame:CGRectZero color:[UIColor clearColor] alignment:NSTextAlignmentCenter];
    [self.downView addSubview:velLabel];
    [velLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.velocityLabel.mas_bottom);
        make.centerX.equalTo(self.velocityLabel.mas_centerX);
        make.height.equalTo(@(20 * SCALEHEIGHT));
    }];
    velLabel.text = @"配速（米/秒）";
    
    //  结束按钮
    if(!self.finshedButton) {
        
        self.finshedButton = [UIButton buttonWithTitle:@"finshed.png" frame:CGRectZero target:self action:@selector(finshedButtonAction)];
        [self.downView addSubview:self.finshedButton];
        [self.finshedButton mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.centerX.equalTo(self.downView.mas_centerX).offset(100 * SCALEWIDTH);
            make.bottom.equalTo(self.downView.mas_bottom).offset(-50 * SCALEHEIGHT);
            make.size.mas_equalTo(CGSizeMake(80 * SCALEWIDTH, 80 * SCALEWIDTH));
        }];
        self.finshedButton.layer.masksToBounds = YES;
        self.finshedButton.layer.cornerRadius = 40 * SCALEWIDTH;
    }
    
    //  暂停按钮
    if (!self.pauseButton) {
        
        self.pauseButton = [UIButton buttonWithTitle:@"pause.png" frame:CGRectZero target:self action:@selector(pauseButtonAction)];
        [self.downView addSubview:self.pauseButton];
        [self.pauseButton mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.centerX.equalTo(self.downView.mas_centerX).offset(-100 * SCALEWIDTH);
            make.bottom.equalTo(self.downView.mas_bottom).offset(-50 * SCALEHEIGHT);
            make.size.mas_equalTo(CGSizeMake(80 * SCALEWIDTH, 80 * SCALEWIDTH));
        }];
        self.pauseButton.layer.masksToBounds = YES;
        self.pauseButton.layer.cornerRadius = 40 * SCALEWIDTH;
    }
}

#pragma mark - 暂停 开始按钮
- (void)pauseButtonAction {
    [UIView animateWithDuration:0.5f animations:^{
        [self.timeLabel pause];
        if (self.isContinue) {
            [self.timeLabel pause];
            [GiFHUD setGifWithImageName:@"restman.gif"];
            [self.pauseButton setBackgroundImage:[[UIImage imageNamed:@"continue.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        } else {
            
            [self.timeLabel start];
            [GiFHUD setGifWithImageName:@"runningman.gif"];
            [self.pauseButton setBackgroundImage:[[UIImage imageNamed:@"pause.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        }
        self.isContinue = !self.isContinue;
    }];
}

#pragma mark - 结束按钮
- (void)finshedButtonAction {
  
    [GiFHUD setGifWithImageName:@"restman.gif"];
    [self.timeLabel pause];
    if (self.isContinue) {
        [self.pauseButton setBackgroundImage:[[UIImage imageNamed:@"continue.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    } else {
        [self.pauseButton setBackgroundImage:[[UIImage imageNamed:@"pause.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    }
    self.isContinue = NO;
    
    
    CGFloat sumDistance = self.distanceLabel.text.floatValue;
    if (sumDistance > 0.10) {
        
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"结束并保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [GiFHUD dismiss];
            [self.navigationController popViewControllerAnimated:YES];
            CGFloat dis =  (self.distanceLabel.text.floatValue * 0.7);
            self.distanceBlock([NSString stringWithFormat:@"%f", dis], self.sumTime);
            
        }];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [GiFHUD setGifWithImageName:@"runningman.gif"];
            [self.timeLabel start];
            if (self.isContinue) {
                [self.pauseButton setBackgroundImage:[[UIImage imageNamed:@"continue.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
            } else {
                [self.pauseButton setBackgroundImage:[[UIImage imageNamed:@"pause.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
            }
            self.isContinue = YES;
        }];
        self.alertController = [UIAlertController alertControllerWithTitle:nil message:@"是否结束本次运动" preferredStyle:UIAlertControllerStyleActionSheet];
        [_alertController addAction:sure];
        [_alertController addAction:cancel];
        
        [self presentViewController:_alertController animated:YES completion:^{
        }];
        
    } else {
        
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"结束运动" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [GiFHUD dismiss];
            [self.navigationController popViewControllerAnimated:YES];
            self.navigationController.tabBarController.tabBar.hidden = NO;
        }];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"继续运动" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [GiFHUD setGifWithImageName:@"runningman.gif"];
            [self.timeLabel start];
            if (self.isContinue) {
                [self.pauseButton setBackgroundImage:[[UIImage imageNamed:@"continue.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
            } else {
                [self.pauseButton setBackgroundImage:[[UIImage imageNamed:@"pause.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
            }
            self.isContinue = YES;
            
        }];
        self.alertController = [UIAlertController alertControllerWithTitle:nil message:@"此次运动距离太短，无法保存， 是否结束本次运动？" preferredStyle:UIAlertControllerStyleActionSheet];
        [_alertController addAction:sure];
        [_alertController addAction:cancel];
        
        [self presentViewController:_alertController animated:YES completion:^{
        }];
    }
   
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
